package com.tl.web02.controller.common_servlet;

import com.tl.web02.config.Config;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

@WebServlet(name = "RegisterServlet", urlPatterns = "/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取参数,将参数保存在servletContext中
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if(!notNullVerify(username)){
            excuteJs(out,"用户名不可以为空", Config.VERSION+"register.jsp");
        }
        if(!notNullVerify(password)){
            excuteJs(out,"密码不可以为空",Config.VERSION+"register.jsp");
        }
        HashMap<String,String> userMap = (HashMap<String,String>)getServletContext().getAttribute("userMap");
        userMap.put(username,password);
        getServletContext().setAttribute("userMap",userMap);
        excuteJs(out,"注册成功",Config.VERSION+"login.jsp");
    }
    public void excuteJs(PrintWriter out,String msg,String action){
        String jsScript = "alert('"+msg+"');window.location.href='"+action+"'";
        System.out.println(jsScript);
        out.println("<script language=\"javascript\">"+jsScript+"</script>");
        out.flush();
        out.close();
    }
    public boolean notNullVerify(String str){
        if(str==null||str.trim().length()==0){
            return false;
        }
        return true;
    }
}
